package whut.pso;

/* author: gandhi - gandhi.mtm [at] gmail [dot] com - Depok, Indonesia */

// just a simple utility class to find a minimum position on a list

import org.apache.commons.math3.stat.StatUtils;
import whut.commons.Location;

import java.io.FileWriter;
import java.util.Set;

public class PSOUtility {
	public static int getMinPos(double[] list) {
		int pos = 0;
		double minValue = list[0];
		
		for(int i=0; i<list.length; i++) {
			if(list[i] < minValue) {
				pos = i;
				minValue = list[i];
			}
		}
		return pos;
	}
	public static double[] normalize(double[] values){
		double[] result = new double[values.length];
		double sum = StatUtils.sum(values);
		if (sum == 0) return result;

		for (int i = 0; i < values.length; i++) {
			result[i] = values[i] / sum;
		}
		return result;
	}


	public static double[][] getXY(double[] loc) {
		int DimA = 1 + (loc.length >> 1);
		int DimB = DimA;

		double frontX = 0, frontY = 0;
		double[] x = new double[DimA];
		double[] y = new double[DimB];
		int half = loc.length >> 1;
		for (int i = 0; i < loc.length; i++) {
			if (i < half) {
				x[i] = loc[i];
				frontX += loc[i];
			} else {
				y[i - half] = loc[i];
				frontY += loc[i];
			}
		}
		x[DimA - 1] = 1 - frontX;
		y[DimB - 1] = 1 - frontY;

		return new double[][]{x, y};
	}

	public static double[][] getXYZ(double[] loc, int nxy, int nz){
		int half = nxy + 1;
		double[] x = new double[half];
		double[] y = new double[half];
		double[] z = new double[nz];
		double frontX = 0, frontY = 0;

		for (int i = 0; i < loc.length; i++) {
			if (i < nxy) {
				x[i] = loc[i];
				frontX += loc[i];
			}else if (i < 2 * nxy) {
				y[i - nxy] = loc[i];
				frontY += loc[i];
			}else{
				z[i - 2 * nxy] = loc[i];
			}
		}

		x[half - 1] = 1 - frontX;
		y[half - 1] = 1 - frontY;

		return new double[][]{x, y, z};
	}

	public static void saveResult(Set<Location> results){
		try {
			FileWriter fileWriter = new FileWriter(".\\Result.txt");
			int i = 1;
			for (Location item : results){
				double[] loc = item.getLoc();
				double[] benefits = item.getExtended();
				StringBuilder strResult = new StringBuilder();
				strResult.append(i++);
				for (int j = 0; j < loc.length; j++) {
					strResult.append(String.format("\t%.6f",loc[j]));
				}
				for (int j = 0; j < benefits.length; j++) {
					strResult.append(String.format("\t%.6f",benefits[j]));
				}
				strResult.append('\n');
//				System.out.print(strResult.toString());
				fileWriter.write(strResult.toString());
			}
			
			fileWriter.flush();
			fileWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
//    private double[] abs(double[] values){
//        double[] result = new double[values.length];
//        for (int i = 0; i < values.length; i++) {
//            result[i] = FastMath.abs(values[i]);
//        }
//        return result;
//    }